//
//  ViewController.m
//  Plist1
//
//  Created by wp w on 12-6-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "DLog.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (IBAction)readRes {
    NSString *path = [self getPlistPath:@"test"];
    
    //资源plist就是一个大的字典
    if(dict == nil)
    {
        dict = [[NSDictionary alloc] 
                initWithContentsOfFile:path];
        Log(@"%@", dict);
    }
}

- (IBAction)readFile {
    NSString *filePath = [self getDocumentsPath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSString *arrPath = [filePath stringByAppendingPathComponent:@"array.plist"];
        NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];
        Log(@"%@", arr);
        
        NSString *dictPath = [filePath stringByAppendingPathComponent:@"dict.plist"];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:dictPath];
        Log(@"%@", dict);
    }
}

- (IBAction)writeFile {
    NSString *filePath = [self getDocumentsPath];
    if (dict != nil) {
        NSString *arrPath = [filePath stringByAppendingPathComponent:@"array.plist"];
        NSMutableArray *marr = [[NSMutableArray alloc] init];
        [marr addObject:[dict objectForKey:@"aString"]];
        [marr addObject:[dict objectForKey:@"bString"]];
        [marr addObject:[dict objectForKey:@"aNum"]];
        [marr addObject:[dict objectForKey:@"bNum"]];
        [marr addObject:[dict objectForKey:@"aDate"]];
        [marr addObject:[dict objectForKey:@"aBool"]];
        [marr writeToFile:arrPath atomically:YES];
        
        NSString *dictPath = [filePath stringByAppendingPathComponent:@"dict.plist"];
        [dict writeToFile:dictPath atomically:YES];
    }
}


- (NSString *)getPlistPath:(NSString *)str{
    //获取资源plist路径
    NSBundle *bundle = [NSBundle mainBundle]; //取得mainBundle
    NSString *plistPath = [bundle pathForResource:str ofType:@"plist"]; //取得文件路径
    Log(@"%@", plistPath);
    return plistPath;
}

- (NSString *)getDocumentsPath{
    //获取document目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    Log(@"%@", paths);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    Log(@"%@", documentsDirectory);
    return documentsDirectory;
}

@end
